﻿using System;
using System.DirectoryServices;

namespace Tool
{
    #region AD域控制类
    /// <summary>
    /// AD域控制类
    /// </summary>
    #endregion
    public class ADDomain
    {
        #region 轻型目录访问协议
        /// <summary>
        /// 轻型目录访问协议
        /// </summary>
        #endregion
        public static string PrefixPath { get; } = "LDAP://";

        #region 查询AD域用户
        /// <summary>
        /// 查询AD域用户
        /// </summary>
        /// <param name="username">要查找的用户名</param>
        /// <returns>查找到的用户架构</returns>
        #endregion
        public static string GetUser(string domain, string username, string password, string find_name)
        {
            try
            {
                // 连接域
                DirectoryEntry de = new DirectoryEntry(PrefixPath + domain, username, password);
                // 创建搜索
                DirectorySearcher deSearch = new DirectorySearcher(de)
                {
                    Filter = "(&(objectClass=user)(cn=" + find_name + "))",
                    SearchScope = SearchScope.Subtree
                };
                // 搜索用户
                SearchResult result = deSearch.FindOne();
                if (result != null)
                {
                    // 返回用户数据
                    return result.GetDirectoryEntry().Path;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        #region 加入域用户至本地用户组
        /// <summary>
        /// 加入域用户至本地用户组
        /// </summary>
        /// <param name="localgroup">本地组名</param>
        /// <param name="domainname">域名称</param>
        /// <param name="username">域用户名</param>
        /// <returns></returns>
        #endregion
        public static string JoinDomainUserToLocalGroup(string localgroup, string domainname, string username)
        {
            try
            {
                string userPath = string.Format("WinNT://{0}/{1},user", domainname, username);
                string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, localgroup);
                using (DirectoryEntry group = new DirectoryEntry(groupPath))
                {
                    group.Invoke("Add", userPath);
                    group.CommitChanges();
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}
